package com.hmdp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private FollowMapper followMapper;
    /**
     *根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("该笔记不存在");
        }
        //查询blog相关用户
        queryBlogUser(blog);
        //查询博客是否被点赞
        isBlogLiked(blog);
        return Result.ok(queryBlogUser(blog));
    }

    /**
     * 判断博客是否点赞
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        Long id = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //判断用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, id.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 点赞功能
     * @param id
     */
    @Override
    public void LikeBlog(Long id) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.判断用户是否已经点赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){
            //1.如果为空，就说明用户拥有点赞资格  ;  添加到数据库里面
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (update){
                //如果数据库添加成功，那么就将对象添加到redis里面
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        } else {
            //2.用户以及点过赞了 ； 那么就取消点赞
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            if (update){
                //1.1.数据库添加成功，将用户移除出redis里面
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
    }

    /**
     * 分页查询热点博客
     * @param current
     * @return
     */
    @Override
    public List<Blog> queryHotBlog(Integer current) {
        Page<Blog> page = query().orderByDesc("liked").page(new Page<> (current, SystemConstants.MAX_PAGE_SIZE));
        List<Blog> list = page.getRecords();
        //查询用户
        list.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return list;
    }

    /**
     * 查出排名前五的点赞用户
     * @param id
     * @return
     */
    @Override
    public Object queryBlogTop5(Long id) {
        //1.根据id将排名前五的用户查询出来
        String key = BLOG_LIKED_KEY + id;
        Set<String> userTop5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (userTop5 == null || userTop5.isEmpty()){
            return Result.ok();
        }
        List<String> users = new ArrayList<>(userTop5);
        List<Long> ids = users.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);

        List<UserDTO> userDTOS = userService.query().in("id",ids).last("ORDER BY FIELD(id,"+join+")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return userDTOS;
    }

    /**
     * 保存博文
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2.保存博文
        blog.setUserId(userId);
        blog.setCreateTime(LocalDateTime.now());
        blog.setUpdateTime(LocalDateTime.now());
        boolean isSuccess = blogMapper.saveBlog(blog);
        //3.如果添加失败，那就返回错误信息
        if (!isSuccess){
            return Result.fail("博文发布失败");
        }
        //4.保存成功，将博文推送给粉丝
        //4.1查询出所有的粉丝账号
        List<Integer> followId = followMapper.selectAllFollow(userId);
        //4.2向所有的粉丝推送信息
        for (Integer followId1 : followId) {
            String key = FEED_KEY + followId1;
            stringRedisTemplate.opsForZSet().add(key,followId1.toString(),System.currentTimeMillis());
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取到当前用户id
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet().
                        reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.解析数据：blogId max offset
        if (typedTuples == null || typedTuples.isEmpty()){
            //3.1如果是空，那么就返回一个空list
            return Result.ok(ListUtil.empty());
        }
        long minTime = 0;
        int os = 1;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //1.获取id
            String id = typedTuple.getValue();
            ids.add(Long.valueOf(id));
            //2.获取分数，时间戳
            long time = typedTuple.getScore().longValue();
            if (time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        //4.根据id查询blog
        String join = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        //5.封装
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
    /**
     * 博客查询用户
     * @param blog
     * @return
     */
    private Blog queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        return blog;
    }
}
